<?php
/**
 * Auth 权限类
 * User: H2H
 * Date: 2018/9/14
 * Time: 17:56
 */

namespace app\common\controller;


class Auth
{
    private static $instance;
    private $userId;
    private $groupId;
    private $rules;
    private $daili_level = ['3','4','5','6']; // 代理级别
    private $root_level = ['1', '2'];   // 管理员级别

    private function __construct($config = [])
    {
        $u_id         = session('userinfo.u_id');
        $this->userId = !empty($u_id) ? $u_id : '';
    }

    private function __clone()
    {
    }

    /**
     * 单例模式入口
     * @param array $config
     * @return Auth
     */
    public static function instance($config = [])
    {
        if (!self::$instance instanceof self) {
            self::$instance = new self($config);
        }
        return self::$instance;
    }

    /**
     * 设置用户id
     * @param $user_id
     * @return Auth
     */
    public function userId($user_id)
    {
        $this->userId = $user_id;
        return $this;
    }

    /**
     * 设置用户组id
     * @param $group_id
     * @return $this
     */
    public function groupId($group_id)
    {
        $this->groupId = $group_id;
        return $this;
    }

    /**
     * 传入规则 单个传字符串 多个传数组
     * @param $rules
     * @return $this
     */
    public function rules($rules)
    {
        $this->rules = $rules;
        return $this;
    }

    /**
     * 获得用户拥有权限规则id
     */
    private function getUserRules()
    {
        $roleModel = new \app\common\model\Role();
        $authModel = new \app\common\model\Auth();

        $this->groupId = !empty($this->groupId) ? $this->groupId : session('userinfo.role_id');
        $where = [
            'id' => $this->groupId,
        ];
        $roleInfo = $roleModel->getOneData(['where' => $where, 'field' => 'role_on']);
        $rulesId = json_decode($roleInfo['role_on'], true);
//        $rulesId = explode(',', $roleInfo['role_on']);
        $rules = $authModel->useIdGetRules($rulesId);

        return $rules;
    }

    /**
     * 多个规则返回过滤后数组，单个规则返回布尔值
     * @return array|bool
     */
    public function vif()
    {
        # 先拿到用户拥有的权限规则 优先级 group_id > user_id > seession(userinfo.u_id)
        $userRules = $this->getUserRules();

        # 如果rules是字符串 则是单个验证，如果是数组，则是批量验证
        if (is_array($this->rules)) {
            $rules = [];
            $vif = array_intersect($userRules, $this->rules);
            foreach ($vif as $v) {
                $rules[$v] = 1;
            }
            return $rules;
        }
        if (is_string($this->rules)) {
            $vif = in_array($this->rules, $userRules);
            return $vif;
        } else {
            echo '出错';
        }

    }

    /**
     * 判断用户组是否属于管理员级别
     * @return bool
     */
    public function isRoot()
    {
        # 判断groupid是否在root列表中
        $this->groupId = !empty($this->groupId) ? $this->groupId : session('userinfo.role_id');

        return in_array($this->groupId, $this->root_level);
    }

    /**
     * 判断用户组是否属于代理级别
     * @return bool
     */
    public function isDaili()
    {
        # 判断groupid是否在daili列表中
        $this->groupId = !empty($this->groupId) ? $this->groupId : session('userinfo.role_id');

        return in_array($this->groupId, $this->daili_level);
    }

    /**
     * 获取管理员组的id
     * @return array
     */
    public function getRootLevel()
    {
        return $this->root_level;
    }

    /**
     * 获取管理员组的id
     * @return array
     */
    public function getDailiLevel()
    {
        return $this->daili_level;
    }

    public function getMenu()
    {
        # 得到当前登录用户有权限的菜单
        $roleModel = new \app\common\model\Role();
        $authModel = new \app\common\model\Auth();

        $this->groupId = !empty($this->groupId) ? $this->groupId : session('userinfo.role_id');
        $where = [
            'id' => $this->groupId,
        ];
        $roleInfo = $roleModel->getOneData(['where' => $where, 'field' => 'role_on', 'order' => 'id DESC']);
        $rulesId = json_decode($roleInfo['role_on'], true);
        $rules = $authModel->useIdGetMenu($rulesId);
        # 重组
        $return = [];

        foreach ($rules as $value) {
            if ($value['parent_id'] == 0){
                $return[$value['id']]['rule'] = $value['auth_rules'];
                $return[$value['id']]['name'] = $value['name'];
            }else{
                $return[$value['parent_id']]['child'][] = [
                    'rule' => $value['auth_rules'],
                    'name' => $value['name'],
                ];
            }
        }
        return $return;
    }
}